<template>
  <div class="oss">
    <div class="uploadWrap">
      <label
        for="upload"
        class="chooseFile"
        :class="{ upLoading: isUploadLoading }"
        >选择图片上传</label
      >
      <input
        type="file"
        multiple
        id="upload"
        class="upload"
        accept="image/*"
        @change="onChange"
        :disabled="isUploadLoading"
        ref="file"
      />
    </div>
    <p class="tip">
      提示：一次可选择多张图片，最多不超过9张（单张图片大小 &lt; 1M）
    </p>
    <ul class="img-container">
      <li
        v-for="item in imgList"
        :key="item"
        :style="{ background: `url(${item}) no-repeat center/contain` }"
      ></li>
    </ul>
  </div>
</template>

<script>
import OSS from 'ali-oss'
const ACCESSKEY = {
  ID: 'LTAI5tNWNXWQAmZhbENZ5r3e', // AccessKey 阿里云控制台查询
  SECRET: 'WcCGvZZIRnuT5kyS2S54XTW6GnknVl' // 阿里云控制台查询
}
export default {
  name: 'Oss',
  data() {
    return {
      client: new OSS({
        region: 'oss-cn-beijing', // Endpoint（地域节点）上控制台进入bucket查询
        bucket: 'my-test-oss-use', // bucket 仓库名
        accessKeyId: ACCESSKEY.ID, // AccessKeyId 阿里云控制台查询
        accessKeySecret: ACCESSKEY.SECRET, // AccessKeySecret 阿里云控制台查询
        cors: true, // 跨域
        secure: true // 安全传输 use https
      }),
      imgList: [], // 上传成功的图片返回的URL
      isUploadLoading: false // 图片是否正在上传
    }
  },
  mounted() {
    // this.getOssImg()
  },
  methods: {
    // 获取 oss 图片
    getOssImg() {
      this.client.list({
        prefix: 'my-test-oss-use/'
      }).then(res => {
        console.log(res)
      })
    },
    // 选择图片
    onChange() {
      const chooseUploadImgs = this.$refs?.file?.files // 选择的图片
      if (chooseUploadImgs.length === 0) {
        return false
      }
      if (chooseUploadImgs.length > 9) {
        alert('大于9张')
        return false
      }
      const uploadImgs = [] // 符合规格的图片
      for (const file of chooseUploadImgs) {
        const size = file.size / 1024 / 1024 // 单位转换为M
        if (size > 1) {
          console.warn('大于1M')
          return false
        }
        uploadImgs.push(file)
      }
      this.uploadFilesByOSS2(uploadImgs)
    },
    // 上传OSS
    uploadFilesByOSS(imgs) {
      this.isUploadLoading = true
      const uploadRequest = [] // promiseAll
      for (const img of imgs) {
        uploadRequest.push(
          new Promise((resolve, reject) => {
            this.client
              .put(`${Math.random()}-${img.name}`, img) // 上传图片
              .then((res) => {
                resolve(res.url) // 返回图片URL
              })
              .catch((err) => {
                reject(err)
              })
          })
        )
      }
      Promise.allSettled(uploadRequest)
        .then((res) => {
          const imgs = []
          for (const item of res) {
            if (item.status === 'fulfilled') {
              imgs.push(item.value)
            }
          }
          this.imgList = imgs
        })
        .catch((err) => {
          console.error(err)
        })
        .finally(() => {
          console.log('finally')
          this.isUploadLoading = false
        })
    },
    // 上传OSS 方法二
    async uploadFilesByOSS2(imgs) {
      this.isUploadLoading = true
      const files = []
      for (const img of imgs) {
        const res = await this.client.put(
          `${Math.random() * 100}-${img.name}`,
          img
        )
        files.push(res.url)
      }
      this.imgList = files
      this.isUploadLoading = false
    }
  }
}
</script>

<style scoped>
.upload {
  display: none;
}
.uploadWrap {
  display: flex;
  justify-content: center;
}
.chooseFile {
  display: block;
  width: 150px;
  height: 50px;
  text-align: center;
  line-height: 50px;
  background-color: #42b983;
  color: #fff;
  border-radius: 5px;
  cursor: pointer;
}
.tip {
  color: #ccc;
}
.img-container > li {
  list-style: none;
  width: 150px;
  height: 100px;
  float: left;
  margin: 0 30px 30px 0;
  border: 1px solid #ccc;
}
.upLoading {
  background-color: #ccc;
}
</style>
